package org.crepi22.finecrop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;


/**
 * @author pierre
 * Utilities to handle files.
 */
public class FileUtil {

    private static final String SEPARATOR = "-"; //$NON-NLS-1$
    private static final String BAK_SUFfIX = ".bak"; //$NON-NLS-1$

    /**
     * Compute a backup filename from an original filename.
     * @param file
     * @return the filename with .bak instead of the original prefix.
     */
    public static File bakFile(File file) {
        String path = file.getAbsolutePath();
        String filename = file.getName();
        // We do not want the extension of a parent if there is no extension
        int pos = filename.lastIndexOf('.') + path.length() - filename.length(); 
        if (pos > 0) {
            path = path.substring(0,pos) + BAK_SUFfIX;
        } else {
            path = path + BAK_SUFfIX;
        }
        return new File(path);
    }
    
    /**
     * Compute a versioned file from an original filename.
     * @param file
     * @param i
     * @return the filename with - <num> appended at the right place before the suffix.
     */
    public static File versionFile(File file, int i) {
        String path = file.getAbsolutePath();
        String filename = file.getName();
        // We do not want the extension of a parent if there is no extension
        int pos = filename.lastIndexOf('.') + path.length() - filename.length();
        if (pos > 0) {
            path = path.substring(0,pos) + SEPARATOR + i + path.substring(pos);
        } else {
            path = path + SEPARATOR + i;
        }
        return new File(path);
    }

    /**
     * Copy file from a path to another.
     *
     * @param sourceFile the source file
     * @param destFile the destination file
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static void copyFile(File sourceFile, File destFile) throws IOException {
        if(!destFile.exists()) {
            destFile.createNewFile();
        }
        FileInputStream fin = new FileInputStream(sourceFile);
        try {
            FileOutputStream fout = new FileOutputStream(destFile);
            try {
                FileChannel source = fin.getChannel();
                try {
                    FileChannel destination = fout.getChannel();
                    try {
                        long count = 0;
                        long size = source.size();
                        while ((count += destination.transferFrom(source, count, size - count)) < size)
                            ;
                    } finally {
                        destination.close();
                    }
                } finally {
                    source.close();
                }
            } finally {
                fout.close();
            }
        } finally { fin.close(); }
    }
    
}
